package ar.com.ford.it.fullEconomics.persistence.dao.query;


import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import com.ford.it.persistence.impl.toplink.CustomExpressionFactory;

public class CostStructureFindQuery implements CustomExpressionFactory {

    public Expression createExpression(ExpressionBuilder builder,
                                       Object[] parameters) {
        Expression exp = null;
        Teess01Supplier supplier = (Teess01Supplier) parameters[0];
        Teesp02Commodity commodity = (Teesp02Commodity) parameters[1];
        Teesp01Part part = (Teesp01Part) parameters[2];

        String supplierClass = supplier.getEess01SupplierClassCodeC();
        String supplierCode = supplier.getEess01SupplierCodeC();
        String prefix = part.getEesp01PartPrefixCodeC();
        String base = part.getEesp01PartBaseCodeC();
        String suffix = part.getEesp01PartSuffixCodeC();
        String partClass = part.getEesp01PartClassCodeC();
        Teesg01Plant plant = part.getEesp01PlantCodeC();

        exp = builder.get("eesc01PlantCodeC").equal(plant);

        if (!supplierClass.equals("-1")) {
            exp = exp.and(builder.get("teess01Supplier").get(
                    "eess01SupplierClassCodeC").equal(supplierClass));
        }
        if(supplierCode != null){
            supplierCode += "%";
            exp = exp.and(builder.get("teess01Supplier").get(
            "eess01SupplierCodeC").like(supplierCode));
        }
        if(commodity != null){
            exp = exp.and(builder.get("teesp02Commodity").equal(commodity));
        }
        if (!partClass.equalsIgnoreCase("-1"))
            exp = exp.and(builder.get("teesp04Supply").get("teesp01Part").get(
                    "eesp01PartClassCodeC").equal(partClass));
        if (prefix != null) {
            prefix += "%";
            exp = exp.and(builder.get("teesp04Supply").get("teesp01Part").get(
                    "eesp01PartPrefixCodeC").toChar().like(prefix));
        }
        if (base != null) {
            base += "%";
            exp = exp.and(builder.get("teesp04Supply").get("teesp01Part").get(
                    "eesp01PartBaseCodeC").toChar().like(base));
        }
        if (suffix != null) {
            suffix += "%";
            exp = exp.and(builder.get("teesp04Supply").get("teesp01Part").get(
                    "eesp01PartSuffixCodeC").toChar().like(suffix));
        }

        return exp;
    }

}
